package com.kkm.controller;

import com.kkm.pojo.PageBean;
import com.kkm.pojo.Song;
import com.kkm.service.Imp.MusicServiceImp;
import com.kkm.service.MusicService;
import com.kkm.util.QiNiu;
import com.kkm.util.QiNiuDown;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/music")
public class MusicServlet extends BaseServlet {
    private MusicService service = new MusicServiceImp();

    //展示音乐
    public void showAllMusic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String currentPage = req.getParameter("currentPage");
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        int rows = 8;
        // req.removeAttribute("currPageMax");
        PageBean<Song> pageBeanMusic = service.showAllMusic(currentPage, rows);
        req.setAttribute("Music", pageBeanMusic);
        req.getRequestDispatcher("/showMusic.jsp").forward(req, resp);
    }

    public void checkMusic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> condition = req.getParameterMap();
        for (String key : condition.keySet()) {
            System.out.println(key + " " + condition.get(key)[0]);
        }

        String currentPage = req.getParameter("currentPage");
        int rows = 8;
        PageBean<Song> pageBeanMusic = service.checkMusic(condition, currentPage, rows);
        req.setAttribute("Music", pageBeanMusic);
        req.getRequestDispatcher("/showMusic.jsp").forward(req, resp);
    }

    //删除音乐
    public void deleteMusic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("id");
        service.deleteMusic(sid);

        String currentPage = req.getParameter("currentPage");
        int rows = 8;
        PageBean<Song> pageBeanMusic = service.showAllMusic(currentPage, rows);
        req.setAttribute("Music", pageBeanMusic);
        req.getRequestDispatcher("/showMusic.jsp").forward(req, resp);
    }

    //修改音乐第一步
    public void checkMusicById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("id");
        Song music = service.checkMusicById(sid);
        System.out.println("歌曲：" + music);
        req.setAttribute("music", music);
        req.getRequestDispatcher("/modifyMusic.jsp").forward(req, resp);
    }

    public void modifyMusic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        System.out.println("歌曲id" + sid);

        Map<String, String[]> condition = req.getParameterMap();
        for (String key : condition.keySet()) {
            System.out.println(key + "=" + condition.get(key)[0]);
        }
        service.modifyMusic(condition, sid);
        String currentPage = req.getParameter("currentPage");
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        int rows = 8;
        // req.removeAttribute("currPageMax");
        PageBean<Song> pageBeanMusic = service.showAllMusic(currentPage, rows);
        req.setAttribute("Music", pageBeanMusic);
        req.getRequestDispatcher("/showMusic.jsp").forward(req, resp);
    }

    /*
     *上传歌曲*/
    public void upLoadSong(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String contentType = req.getContentType();
        System.out.println("req.getContentType()  =  " + contentType);
        boolean b = contentType.startsWith("multipart/form-data");
        System.out.println("form表单是否设置enctype=\"multipart/form-data\"   " + b);
        InputStream ins = null;
        Song song = new Song();
        //确认该操作是否支持文件上传操作，enctype="multipart/form-data"
        if (b) {
            //创建磁盘工厂对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //创建servlet文件上传核心对象
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            try {
                //使用servlet文件上传核心对象 ServletFileUpload 解析request请求，获取请求中表单提交过来的数据（所有input）
                List<FileItem> fileItemList = servletFileUpload.parseRequest(req);
                //非文件元素
                Map<String, String> map = new HashMap<>();
                List<String> url = new ArrayList<>();
                //遍历fileItemList
                for (FileItem fileItem : fileItemList) {
                    System.out.println(fileItem + "1sa51d5as1d5");
                    //判断input的type 是 file类型 还是 非file类型
                    if (fileItem.isFormField()) {  // true 为 非file类型  false 为 file类型
                        String name = fileItem.getFieldName();
                        String value = fileItem.getString("UTF-8");
                        map.put(name, value);

                    } else {
                        ins = fileItem.getInputStream();// 获取文件输入流（读数据）
                        String upload = QiNiu.upload(ins);
                        String s = QiNiuDown.publicFile(upload, "qzzqmzsyw.hb-bkt.clouddn.com");

                        String http_url = "http://" + s;//拼接直链
                        url.add(http_url);
                        System.out.println("当前文件直链为:" + http_url);
                    }
                }

                for (String s : map.keySet()) {
                    System.out.println(s + "0000" + map.get(s));
                    song.setName(map.get("muSinger") + "-" + map.get("muName"));
                    song.setLyric(map.get("muGeci"));
                }
                song.setUrl(url.get(0));
                song.setPic(url.get(1));
                System.out.println("hhhhhhhhhh/////song:" + song);
                int update = service.addMusic(song);
                System.out.println(update + "sddasdasd");

            } catch (FileUploadException e) {
                e.printStackTrace();
            }

        }
        resp.getWriter().write("<script language='javascript'>alert('上传成功！');" +
                "window.location.href='/addMusic.jsp';</script>");
    }
}


